package dijjer.io.xfer.http;

import java.io.IOException;
import java.io.Reader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import dijjer.io.xfer.http.handlers.DownloadHandler;
import dijjer.io.xfer.http.handlers.GraphGIFHandler;
import dijjer.io.xfer.http.handlers.ShutdownHandler;
import dijjer.io.xfer.http.handlers.StatusPageHandler;
import dijjer.io.xfer.http.handlers.UpdateHandler;

public abstract class PageHandler {

	public static final String VERSION = "$Id: PageHandler.java 2 2008-03-21 14:33:03Z ian.clarke $";
	private static final Map _handlers = new HashMap();
	private static final StatusPageHandler DEFAULTPAGEHANDLER = new StatusPageHandler();

	static {

		GraphGIFHandler graph = new GraphGIFHandler();

		registerHandler(null, "/graph.gif[?]?", graph);
		registerHandler(null, ".*dijjer_install_check.gif", graph);
		registerHandler(null, "/shutdown.*", new ShutdownHandler());
		registerHandler(null, "/update", new UpdateHandler());
		registerHandler(null, "/http:/.*", new DownloadHandler());
	}

	public static void setDefaultPageField(String name, String value) {
		DEFAULTPAGEHANDLER.setTemplateField(name, value);
	}

	protected HTTPResponse dumpError(int code, String message, String page)
	{
		try {
			return new HTTPExceptionResponse(new HTTPException(code, message, page));
		} catch (IOException e) {
			throw new HTTPException(code, message, page);
		}
	}

	public static void registerHandler(String method, String url, PageHandler handler) {
		Map methods = (Map) _handlers.get(method);
		if (methods == null) {
			methods = new HashMap();
			_handlers.put(method, methods);
		}
		methods.put(url, handler);
	}

	public static PageHandler getHandler(String method, String url)
	{
		Map methods = (Map) _handlers.get(method);
		if (methods == null) {
			methods = (Map) _handlers.get(null);
		}
		if (methods == null) {
			return DEFAULTPAGEHANDLER;
		}
		PageHandler handler = (PageHandler) methods.get(url);
		if (handler == null) {
			for (Iterator i = methods.keySet().iterator(); i.hasNext();) {
				String pageString = (String) i.next();
				if (url.matches(pageString)) {
					handler = (PageHandler) methods.get(pageString);
					break;
				}
			}
		}
		if (handler == null) {
			handler = (PageHandler) methods.get(null);
		}
		if (handler == null) {
			return DEFAULTPAGEHANDLER;
		}
		return handler;
	}

	protected String getParam(Map params, String paramName)
	{
		List paramList = (List) params.get(paramName);
		if (paramList != null && paramList.size() > 0) {
			return (String) paramList.get(0);
		}
		return null;
	}

	public abstract HTTPResponse handleRequest(String method, String url, Map params, Map headers, Reader in);
}
